package com.kxn.multi.module.common.util;

import com.kxn.multi.module.common.exception.ServiceException;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class BeanUtils {

    public static <T> T sourceToTarget(Object source, Class<T> target){
        if(source == null){
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            org.springframework.beans.BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            throw new ServiceException("convert bean error");
        }

        return targetObject;
    }

    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){
        if(sourceList == null){
            return null;
        }

        List targetList = new ArrayList<>(sourceList.size());
        try {
            for(Object source : sourceList){
                T targetObject = target.newInstance();
                org.springframework.beans.BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e){
            throw new ServiceException("convert bean error");
        }

        return targetList;
    }

    public static <T> T map2Bean(final Map<String, ? extends Object> map, final Class<T> clazz) {
        if (map == null) {
            return null;
        }
        T res = null;
        try {
            res = clazz.getDeclaredConstructor().newInstance();
            //获取到所有属性，不包括继承的属性
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                //获取字段的修饰符
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                //设置对象的访问权限
                field.setAccessible(true);
                //根据属性名称去map获取value
                if(map.containsKey(field.getName())) {
                    //给对象赋值
                    field.set(res, map.get(field.getName()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
